<template>
  <div class="custom-tab-page">
    <div class="tab3-title">
      <div class="left">联系人</div>
      <el-button v-if="permissions" size="small" class="right" type="primary" @click="addFun">
        <el-icon>
          <IEpPlus />
        </el-icon>
        添加</el-button>
    </div>
    <el-table :data="tableData" border style="width: 100%; margin-top: 15px">
      <el-table-column v-for="item in headList" :prop="item.field" :label="item.name" />
      <el-table-column width="120" label="操作" align="center" v-if="permissions">
        <template #default="{ row }">
          <el-button type="primary" @click="openUpdate(row)" link>
            编辑
          </el-button>
          <el-button type="danger" link @click="delFun(row)"> 删除 </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="display: flex; justify-content: center; margin-top: 10px">
      <el-pagination :small="true" v-model:currentPage="currentPage" v-model:page-size="pageSize"
        :page-sizes="[20, 50, 100, 200]" layout="total, prev, pager, next, jumper" :total="total"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </div>
  </div>
  <!-- 添加表单 -->
  <el-dialog width="30%" v-model="dialogVisible" :title="title" :before-close="handleClose">
    <formPage ref="formPageRef" @submitFun="submitFun" @closeForm="closeForm" :formList="formData" :btnType="true" />
  </el-dialog>
</template>
<script setup>
import {
  listApi,
  delApi,
  addApi,
  saveApi,
} from "@/plugins/api/customer/manage/contacts";
import { listApi as dictApi } from "@/plugins/api/system/dict";
import { contactsApi } from "@/plugins/api/customer/setup/fifth";
import { useCounterStore } from "@/stores/counter.js";
const store = useCounterStore();
let permissions = computed(() => {
  let arr = store.userInfo.auth || []
  // || arr.indexOf('boss') > -1
  if (arr.indexOf('manager') > -1) {
    return true
  } else {
    return false
  }
})
const props = defineProps({
  dataInfo: {
    type: Object,
    default: {},
  },
  showItem: {
    type: Boolean,
    default: false,
  },
});
let tableData = ref([]);
const headList = computed(() => {
  return tableHead.value.filter((item) => {
    return item.in_list == 1;
  });
});
// 获取联系人数据
let tableHead = ref([]);

// 获取表单数据
let formList = ref([]);
let formData = computed(() => {
  return formList.value;
});
function getTopData(is_sys) {
  return new Promise((resolve, reject) => {
    contactsApi({
      is_sys: is_sys,
    }).then((data) => {
      resolve(data);
    });
  });
}
function getForm() {
  formList.value = [];
  return Promise.all([getTopData(1), getTopData(0)]).then((res) => {
    if (res.length == 2) {
      let arr_0 = res[0]
        .filter((item) => {
          return item.in_form == 1;
        })
        .map((ele) => {
          return {
            field_id: ele.field_id,
            dict_id: ele.dict_id,
            label: ele.name,
            prop: ele.field,
            formType: ele.form_type,
            required: ele.is_null == 1 ? true : false,
            rulesMessage: ele.input_tips || ele.name,
            placeholder: ele.input_tips || ele.name,
            // termList: ele.termList,
          };
        });
      let arr_1 = res[1]
        .filter((item) => {
          return item.in_form == 1;
        })
        .map((ele) => {
          return {
            field_id: ele.field_id,
            dict_id: ele.dict_id,
            label: ele.name,
            prop: ele.field,
            formType: ele.form_type,
            required: ele.is_null == 1 ? true : false,
            rulesMessage: ele.input_tips || ele.name,
            placeholder: ele.input_tips || ele.name,
            // termList: ele.termList,
          };
        });

      formList.value = [...arr_0, ...arr_1];
    }
  });
}
// 获取字典项
function getDictionary(id, dict_id, list) {
  return new Promise((resolve, reject) => {
    dictApi({ dict_id: dict_id }).then((data) => {
      if (list) {
        list.forEach((item) => {
          if (item.field_id == id) {
            item.termList = data.map((ele) => {
              return {
                name: ele.name,
                value: ele.name,
              };
            });
          }
        });
      }
      resolve(data);
    });
  });
}
function getTerm(arr) {
  if (!Array.isArray(arr)) return;
  arr.forEach((item) => {
    if (
      item.formType == "select" ||
      item.formType == "radio" ||
      item.formType == "checkbox"
    ) {
      getDictionary(item.field_id, item.dict_id, arr);
    }
  });
}
// 分页
const currentPage = ref(1);
const pageSize = ref(20);
const total = ref(0);
const handleSizeChange = (val) => {
  pageSize.value = val;
  getData()
};
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getData()
};
function getData() {
  return new Promise((resolve, reject) => {
    listApi({
      page: currentPage.value,
      pageSize: pageSize.value,
      customer_id: props.dataInfo.id,
    }).then((res) => {
      tableHead.value = res.fields;
      tableData.value = res.list;
      total.value = res.page.total;
      resolve(res);
    });
  });
}
// 增加
let dialogVisible = ref(false);
let title = ref("");
let titleType = ref("");
let formPageRef = ref(null);
function addFun() {
  title.value = "新增";
  titleType.value = "add";
  dialogVisible.value = true;
  nextTick(() => {
    formPageRef.value.initFun();
  });
}
function handleClose(done) {
  ElMessageBox.confirm("是否确定关闭此对话框?")
    .then(() => {
      done();
    })
    .catch(() => { });
}
function closeForm() {
  dialogVisible.value = false;
}
// 编辑
let selectData = ref("");
function openUpdate(row) {
  selectData.value = { ...row };
  title.value = "编辑";
  titleType.value = "update";
  dialogVisible.value = true;
  nextTick(() => {
    formPageRef.value.updateFun(row);
  });
}
// 提交
function submitFun(data) {
  let obj = {
    customer_id: props.dataInfo.id,
    ...data,
  };
  if (titleType.value == "add") {
    addApi(obj).then((res) => {
      ElMessage.success("添加成功！");
      dialogVisible.value = false;
      getData();
    });
  } else {
    obj.id = selectData.value.id;
    saveApi(obj).then((res) => {
      ElMessage.success("修改成功！");
      dialogVisible.value = false;
      getData();
    });
  }
}
// 删除
function delFun(row) {
  ElMessageBox.confirm("确认删除，是否继续?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      delApi({
        id: row.id,
      }).then(() => {
        ElMessage({
          type: "success",
          message: "删除成功！",
        });
        getData();
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消。",
      });
    });
}
function initFun() {
  getData();
  getForm().then(() => {
    getTerm(formList.value);
  });
}
defineExpose({
  initFun,
});
//
onMounted(() => {

});
</script>

<style lang="scss" scoped>
.custom-tab-page {
  width: 100%;

  .tab3-title {
    display: flex;
    justify-content: space-between;
    height: 46px;
    background: #fafbfc;
    box-sizing: border-box;
    padding-right: 10px;

    .left {
      align-self: center;
      font-size: 14px;
      font-weight: bold;
      color: #172b4d;
      position: relative;
      padding-left: 7px;

      &::before {
        content: "";
        width: 2px;
        height: 15px;
        background: #005ecc;
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
      }
    }

    .right {
      align-self: center;
    }
  }
}
</style>
